﻿// (c) Copyright Mikhail Dikov. All other rights reserved.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.WebControls;
using System.Web.UI;

namespace WebPartExtenderToolkit
{
    class ZoneExtenderEditorPart : EditorPart
    {
        public ZoneExtenderEditorPart()
        {
            this.Title = "Target WebPartZone";
        }

        protected DropDownList TargetControlID;

        protected override void CreateChildControls()
        {
            Controls.Clear();
            TargetControlID = new DropDownList();
            TargetControlID.ID = "TargetControlID";

            this.Controls.Add(TargetControlID);
        }
        
        protected override void OnPreRender(EventArgs e)
        {
            base.OnPreRender(e);
            WebPartManager wpm = WebPartManager.GetCurrentWebPartManager(Page);
            if (TargetControlID != null && wpm.Zones != null)
            {
                // DisplayTitle gets rendered later so we need to update the list with the actual DiplayTitle
                foreach (WebPartZone targetWebPartZone in wpm.Zones)
                {
                    var item = TargetControlID.Items.FindByValue(targetWebPartZone.ID);
                    if (item != null)
                    {
                        item.Text = targetWebPartZone.DisplayTitle;
                    }
                }
            }
        }

        public override void SyncChanges()
        {
            EnsureChildControls();

            WebPartManager wpm = WebPartManager.GetCurrentWebPartManager(Page);

            if (TargetControlID == null || wpm ==null) return;

            if (TargetControlID.Items.Count == 0)
            {   
                foreach (WebPartZone targetWebPartZone in wpm.Zones)
                {
                    TargetControlID.Items.Add(new ListItem(targetWebPartZone.ID, targetWebPartZone.ID));
                }
            }

            IExtenderWebPart wp = WebPartToEdit as IExtenderWebPart;
            if (wp != null)
            {
                TargetControlID.SelectedValue = wp.TargetControlID;
            }
        }

        public override bool ApplyChanges()
        {
            EnsureChildControls();
            IExtenderWebPart wp = WebPartToEdit as IExtenderWebPart;
            if (TargetControlID == null || wp == null) return false;

            wp.TargetControlID = TargetControlID.SelectedValue;
            return true;
        }

    }
}
